from airtest.core.api import *
from poco.drivers.android.uiautomation import AndroidUiautomationPoco
import logging
import requests
import cv2
from rapidfuzz import fuzz
import random
# import sys
from multiprocessing import Process, Queue
import re
from threading import Thread
import subprocess

logging.getLogger("airtest").setLevel(logging.ERROR)
# 创建一个logger
logger = logging.getLogger("头条")
logger.setLevel(logging.DEBUG)


def get_devices_list():
    """获取所有在线设备

    Returns:
        _type_: 设备列表
    """
    res = subprocess.run("adb devices",
                         capture_output=True,
                         text=True,
                         shell=True)
    # print(res.stdout, res.stderr)
    result = res.stdout
    result = result.splitlines()[1:]
    logger.info(result)
    devices_list = []
    for res in result:
        device = res.split('\t')[0]
        if device != '':
            devices_list.append(device)
    return devices_list


class toutiao():

    def __init__(self, dev):
        ###################初始化###################
        self.dev = connect_device(
            f"android://127.0.0.1:5037/{dev}"  #?cap_method=javacap&touch_method=adb
        )

        # if dev:
        self.dev.wake()
        start_app("com.ss.android.article.lite")
        self.poco = AndroidUiautomationPoco(device=self.dev,
                                            use_airtest_input=True,
                                            screenshot_each_action=False)
        self.width, self.height = self.poco.get_screen_size()
        self.start_point = (self.width / 5, self.height * 0.8)  # 中点偏上位置
        self.end_point = (self.width / 5, self.height * 0.3)  # 中点偏下位置
        self.left_point = (self.width * 0.2, self.height / 2)
        self.right_point = (self.width * 0.8, self.height / 2)
        self.first_start = True
        # 创建一个handler，用于写入日志文件
        fh = logging.FileHandler(f"./log/{dev}_log.txt", encoding="utf-8")
        fh.setLevel(logging.DEBUG)
        # 再创建一个handler，用于输出到控制台
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)  # 设置控制台日志级别
        # 定义handler的输出格式
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        fh.setFormatter(formatter)
        ch.setFormatter(formatter)
        # 给logger添加handler
        logger.addHandler(fh)
        logger.addHandler(ch)
        logger.info(dev)

    def poco_judge_page(self) -> bool:
        freeze_poco = self.poco.freeze()
        if freeze_poco(text="开宝箱得金币").exists():
            freeze_poco(text="开宝箱得金币").click()
            return False

        if freeze_poco(textMatches="看视频.*?金币").exists():
            freeze_poco(textMatches="看视频.*?金币").click()
            return False

        if freeze_poco(textMatches=".*?秒后可领奖励").exists():
            if freeze_poco(text="继续观看").exists():
                freeze_poco(text="继续观看").click()
            # self.poco(textMatches=".*?秒后可领奖励").wait_for_disappearance()
            while self.poco(textMatches=".*?秒后可领奖励").exists():
                pass
            keyevent("back")
            return False

        if freeze_poco(text="领取成功").exists():
            freeze_poco(text="领取成功").click()
            # keyevent("back")
            return False

        if freeze_poco(textMatches="逛街再领.*?金币").exists():
            freeze_poco(textMatches="逛街再领.*?金币").click()
            # keyevent("back")
            return False

        if freeze_poco(textMatches=r"\+.*?金币").exists():
            self.poco(textMatches=r"\+.*?金币").wait_for_disappearance()
            keyevent("back")
            return False

        if freeze_poco(text="立即下载").exists():
            keyevent("back")
            return False
        
        if freeze_poco(text="开心收下").exists():
            freeze_poco(text="开心收下").click()
            return False

        return True

    def swipe_up(self):
        logger.info("↑" * 10)
        swipe(self.start_point, self.end_point, duration=0.5)

    def loop(self):
        while 1:
            if self.poco_judge_page():
                self.swipe_up()
            sleep(2)


def start(dev):
    tt = toutiao(dev)
    tt.loop()


if __name__ == '__main__':
    devs = get_devices_list()
    print(devs)
    p_list = []
    for d in devs:
        p = Process(target=start, args=(d, ))
        p_list.append(p)
        p.start()
    for p in p_list:
        p.join()